$(function(){
// 客户自动搜索填充开始
	$("#customerName").autocomplete("/a/ajax/search/customer", {
		delay: 500
		, formatItem:function(item, index, total, query){
	    	return item.townName + " " + item.villageName + " " + item.customerName;
	    }
		, formatResult:function(item){
	    	return item.customerName;
	    }
		, dataType:'json'
		, parse:function(data) {
             return $.map(data, function(item) {
                     return {
                             data: item,
                             value: item.customerName,
                             result: item.customerName
                     }
        	}); // end map
		} // end parse

	}).result(function(event, data, formatted) {
		if(data.mobile != undefined && data.mobile.length > 0) {
			$("#mobile").val(data.mobile);
		}
		else {
			$("#mobile").val(data.tel);
		}
		$("#villageId").val(data.villageId);
		$("#villageSelector").html(data.townName + " " + data.villageName);
	}); // end result
	//客户自动搜索填充结束
	goods.init();
});
function Goods() {
	_this = this;
	// 初始化商品搜索框
	this.init = function() {
		//商品搜索开始
		defaultKeys('goodsKey').focus().dblclick(function(){
			choiceGoods.showGoods(function(id){
				var c = $('#count_'+id).val();
				if(c==0) {
					alert('本商品没有库存了！');
					return ;
				}
				_this.addSellItem(id);
			});
		}).keydown(function(event){ // 搜索并显示结果列表
			// 如果没有关键词则显示商品筛选列表
			if(event.keyCode == KEY.ENTER) {
				choiceGoods.showGoods(function(id){
					var c = $('#count_'+id).val();
					if(c==0) {
						alert('本商品没有库存了！');
						return ;
					}
					_this.addSellItem(id);
				});
			}
		});
		$(document).keydown(function(){
			if(event.keyCode == KEY.ESC) {
				choiceGoods.hide();
				hide();
			}
		});
	};
	this.addSellItem = function(id) {
		if($('.sellItem').find("#"+id).length>0) {
			alert('此商品已经加入到销售列表！请选择其他商品或按ESC退出。');
			return ;
		}
		if(id!=undefined && id.length>0) {
			$.get('/a/ajax/sell/sellItem?r='+new Date()+"&id="+id, function(data) {
				$('.sellItem table').append(data).each(function() {
					// 自动计算订单价格
					autoCalculate();
					// 绑定价格表单事件以实现自动计算价格
					$(".sellItem").find("input[type=text][name=sell_item]").each(function(){
						$(this).focus(); // 让输入焦点进入商品价格输入框
						$(this).bind('keyup', function(){
							autoCalculate();
						});
					});
					$(".sellItem").find("select[name=number]").each(function(){
						$(this).change(function(){
							autoCalculate();
						});
					});
				 });
				choiceGoods.hide();
			});
		}
	};
	this.removeItem = function(o) {
		$(o).parent().parent().remove();
		//自动计算订单价格
		autoCalculate();
		$('#goodsKey').focus();
	};
	// 计算订单价格
	function autoCalculate() {
		var i = 0;
		$(".sellItem").find("input[type=text][name=sell_item]").each(function(){
			var p = parseInt($(this).val()); // 单价
			var id = $(this).parent().attr('id');
			var n = $('#number_'+id).val(); // 选中的数量
			i += p*n;
		});
		$("#payables").val(i);
		$("#realPayables").val(i);
	};
	// 保存订单
	this.saveBill = function() {
		var data = '{"customerName":"';
		data += $('#customerName').val();
		data += '","payables":';
		data += $('#payables').val();
		data += ',"mobile":"';
		data += $('#mobile').val();
		data += '","realPayables":';
		data += $('#realPayables').val();	
		data += ',"villageId":"';
		data += $('#villageId').val();
		data += '"';
		data += ',"memo":"';
		data += $('#memo').val();
		data += '"';
		if($('#needPrint').is(':checked')) {
			data += ',"needPrint":"true" ';
		} else {
			data += ',"needPrint":"false" ';
		}
		var npup = $('input[name=needPrintUnitPrice]:checked').val();
		if(npup == 'true') {
			data += ',"needPrintUnitPrice":"true" ';
		} else {
			data += ',"needPrintUnitPrice":"false" ';
		}
		var items = ',"itemList":[';
		$(".sellItem").find('input[name=sell_item]').each(function(){
			var id = $(this).attr('id');
			var storehouseId = $('#storehouseId_' + id).val();
			var number = $('#number_' + id).val();
			var price = $(this).val();
			if(price==undefined || price.length<=0) {
				price = 0;
			}
			items += '{"goodsId":"'+id+'","payables":'+price+',"number":'+number+',"storehouseId":"'+storehouseId+'"},';
		});
		items = items.substring(0, items.length-1);
		items += ']'
		data += items;
		data +="}";
		var jsondata = $.parseJSON(data);
		if(jsondata.realPayables > jsondata.payables) {
			alert('实际支付金额(折后总价)不能大于商品总价！');
			return ;
		}
		$("#save").attr('disabled', 'disabled');
		$.ajax({
			url:'/a/sell/save-bill'
				, data:{json:data}
				, type:'POST'
				, success:function(d) {
					var rs = $.parseJSON(d);
					if(rs.succeed) {
						payment.showForm(rs.data.billId, goBackURL);
					} else {
						g.showErrorMsg(rs.msg);
					}
					$("#save").removeAttr('disabled');
				}
				, error:function(){
					g.showErrorMsg(MSG.ERR);
					$("#save").removeAttr('disabled');
				}
		});
		/*
		$.post('/a/sell/save-bill', 
				{json : data},
				function(d) {
					var rs = $.parseJSON(d);
					if(rs.succeed) {
						payment.showForm(rs.data.billId, goBackURL);
					} else {
						g.showErrorMsg(rs.msg);
					}
				});
				*/
		// end post
	};
	function goBackURL() {
		var backURL = $("#backURL").val();
		if(backURL != undefined && backURL.length > 0) {
			window.location.href=(backURL);
		} else {
			window.location.href=('/a/sell/list');
		}
	};
	var dt/*弹出层内容*/, bg/*透明背景*/, _this;
	_this = this;
	function hide() {
		aju.removeAll([dt,bg,$('.tip-yellow')]);
		$('#ajaxClose').remove();
	};
	this.chooseStorehouse = function(gid, alink) {
		var url='/a/ajax/sell/choose-storehouse';
		bg = aju.ajaxBg(function() {
			$.ajax({
				data:{gid:gid}
				,type:'GET'
				,url:url
				,success:function(data){
					dt = aju.ajaxData().css({'width':'50%','height':'auto'});
					dt.html(data);
					aju.positionCenter(dt);
					// 显示关闭按钮并绑定关闭时间
					aju.ajaxClose(dt).click(function(){
						hide();
					});
					$('input[name=button]').click(function(){
						var c = $('#storehouseCount').val();
						var sh = dt.find('.slt'); // 被选中的库房
						var shid = sh.attr('id')+'';
						var shname = sh.html();
						shname = shname.substring(0, shname.indexOf('('));
						$('#storehouseId_'+gid).val(shid);
						$(alink).html('库房：'+shname);
						//
						var c = $('#c'+shid).val();
						var s = c;
						if(s>500){ // 最多可选500个
							s=500;
						}
						var cc = $('#number_'+gid).find("option:selected").val();
						$('#number_'+gid).empty();
						if(s>0){
							for(var i=1; i<=s; i++) {
								if(cc == i) {
									$('#number_'+gid).append('<option value="'+i+'" selected>'+i+'</option>')
								} else {
									$('#number_'+gid).append('<option value="'+i+'">'+i+'</option>')
								}
							}
						}
						hide();
						var _cc = $('#number_'+gid).find("option:selected").val();
						if(cc != _cc) { // 如果库房变了且出货数量也变了则重新计算价格
							autoCalculate();
						}
					});
					$('#storehouseList').find('em').each(function(){
						var shid=$(this).css({'padding':'0px 21px'}).attr('id');
						var c = $('#c'+shid).val();
						if(c==0) {
							$(this).poshytip({
								content:'库房商品数量为0！',
								className: 'tip-yellow',
								alignTo: 'target',
								alignX: 'center',
								alignY: 'top',
								offsetY: 5	,
							});
						}
						$(this).click(function() {
							var shid=$(this).attr('id');
							var c = $('#c'+shid).val();
							var s = c;
							if(s>500){ // 最多可选500个
								s=500;
							}
							if(s==0){
								return ;
							}
							$(this).parent().find('em').removeClass('slt');
							$(this).addClass('slt');
							$('#number').empty();
							if(s>0){
								var _s = $('#number_'+gid).find("option:selected").val();
								for(var i=1; i<=s; i++) {
									if(i == _s) {
										$('#number').append('<option value="'+i+'" selected>'+i+'</option>')
									} else {
										$('#number').append('<option value="'+i+'">'+i+'</option>')
									}
								}
								$('#storehouseCount').val('1');
							} else {
								$('#storehouseCount').val('0');
							}
							$("#number").bind('change', function(){
								var cc = $(this).find("option:selected").val();
								$('#storehouseCount').val(cc);
							});
						});
					});	
				},error:function(){
					alert(MSG.ERR);
				}
			});
		});
	};
}
var goods = new Goods();
$(function(){
	$('#save').click(function(){
		goods.saveBill();
	});
});